package com.badibadi.activity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.json.JSONException;

import com.badibadi.fragment.ActivityMyActivityFragment0;
import com.badibadi.fragment.ActivityMyActivityFragment0.getFragmentData;
import com.badibadi.fragment.CalendarFragment;
import com.badibadi.fragment.CalendarFragment.CalendarGridViewAdapter;
import com.badibadi.fragment.CalendarFragment.getAdapter;
import com.badibadi.infos.Activity_Overview_Model;
import com.badibadi.infos.ClueTypeModel;
import com.badibadi.infos.Results;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.JSONUtils;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.TabHostUtils;
import com.badibadi.mytools.Utils;
import com.badibadi.uniclubber.R;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.content.Intent;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 我的活动 修改时间2014-8-28
 * 
 * @author Administrator return_btn index_btn
 */
public class CalendarMyActivityActivity extends BaseActivity implements
		OnClickListener {
	private RelativeLayout bottom_btn1, bottom_btn2;
	// /...黄色是当天，淡蓝色是点击瞬间，深蓝是有活动的天，开始一个标签，结束一个标签
	private TabHost tabhost;
	private TabHost tabhost2;
	public CalendarFragment calendarFragment;
	// private CalendarListFragment calendarListFragment;
	private ActivityMyActivityFragment0 fragment0;
	private FragmentManager manager;
	private Bundle bun;
	// 添加开始年月日button的判断的int类型
	private int StartYY, StartMM, StartDD;
	private int EndYY, EndMM, EndDD;
	private int Judge_YY, Judge_MM, Judge_DD;
	private String d_content;
	// 保存从查询出传过来的东西
	private ClueTypeModel clueTypeModel;
	private List<Activity_Overview_Model> models, models_1;
	private String uid = "1";
	private String fid = "-1";
	private TextView calendar_title;
	// private LinearLayout Keyword_Frame;
	// private boolean is_canyu = true;// true为发起，false为参与
	private boolean is_rili = false;// 判断是否是日历模式
	private Results results;
	private List<Activity_Overview_Model> overview_Models_starttt;
	private Calendar calendar;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				calendar_title.setText(msg.getData().getString("tital_name"));
				break;
			case 3:
				try {
					Utils.ExitPrgress(CalendarMyActivityActivity.this);
					is_rili = true;
					Constants.is_initiator = true;
					FragmentTransaction transaction = manager
							.beginTransaction();
					calendarFragment = CalendarFragment.getInstance();
					// /**
					// * 在这里获取到列表模式中的数据，保存到activity的models当中中，然后通过另一个接口存放到日历模式当中
					// */
					if (!overview_Models_starttt.isEmpty()) {
						for (int i = 0; i < overview_Models_starttt.size(); i++) {//
							// 判断是访问用户是参与者还是发起者（a_uid,uid均为活动发起者id,需判断哪个不为空）
							if (overview_Models_starttt.get(i).getA_uid() != null) {
								if (uid.equals(overview_Models_starttt.get(i)
										.getA_uid())) {
									models.add(overview_Models_starttt.get(i));// 发起者
								} else {

								}
								models_1.add(overview_Models_starttt.get(i));// 参与者
							} else {
								if (uid.equals(overview_Models_starttt.get(i)
										.getUid())) {
									models.add(overview_Models_starttt.get(i));// 发起者
								} else {

								}
								models_1.add(overview_Models_starttt.get(i));// 参与者
							}
						}

//						   
//								+ models_1.size());
					} else {
//						   
					}
					calendarFragment
							.setOnCalendarOnClistener(new CalendarFragment.CalendarListener() {

								@Override
								public boolean AddStartButton(int Year,
										int Month, int Day) {

									return ShowStartButton(Year, Month, Day,
											StartYY, StartMM, StartDD);

								}

								@Override
								public boolean AddEndButton(int Year,
										int Month, int Day) {
									return ShowEndButton(Year, Month, Day,
											EndYY, EndMM, EndDD);
								}

								@Override
								public String AddActivity(int Year, int Month,
										int Day) {
									if (Constants.is_initiator) {
										return ShowActivity(Year, Month, Day,
												models);
									} else {
										return ShowActivity(Year, Month, Day,
												models_1);
									}
								}
							});
					bun = new Bundle();
					bun.putString("uid", uid);
					bun.putString("fid", fid);
					calendarFragment.setArguments(bun);
					transaction.replace(R.id.calendar_layout, calendarFragment);
					transaction.commit();
				} catch (Exception e) {
				}
				break;
			// case 4:
			// try {
			// Utils.ExitPrgress(CalendarMyActivityActivity.this);
			// Utils.showMessage(CalendarMyActivityActivity.this,
			// getResources().getString(R.string.l_xa10));
			// } catch (Exception e) {
			// }
			// break;

			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		goToTheTitle();
		setContentView(R.layout.calendar);
		this.findViewById(R.id.calendar_return_btn).setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						finish();
					}
				});
		uid = initUid(uid);
		fid = initFid(fid);
		uid = getIntent().getStringExtra("uid");
		fid = getIntent().getStringExtra("fid");
		if (uid == null) {
			uid = "1";
		}
		if (fid == null) {
			fid = "-1";
		}
		init();
		LoadFragment(1);
	}

	@Override
	protected void onStart() {
		super.onStart();
		Constants.Activity_tital_handler = handler;
	}

	/**
	 * 重写更新uid和fid
	 * 
	 * @param uid
	 * @param fid
	 */

	public String initUid(String uid) {
		return uid;
	}

	/**
	 * 重写更新uid和fid
	 * 
	 * @param uid
	 * @param fid
	 */

	public String initFid(String fid) {
		return fid;
	}

	/**
	 * 要重写的第一处（初始化为tabhost2）
	 * 
	 * @param id
	 * @param id2
	 */
	protected void initTabHostTWO(int id, int id2) {
		manager = getSupportFragmentManager();
		tabhost2.setVisibility(View.GONE);
		tabhost.setVisibility(View.VISIBLE);
		tabhost.setup();
		tabhost.addTab(tabhost
				.newTabSpec("calendar_tabhost one")
				.setIndicator(getResources().getString(id),
						getResources().getDrawable(R.drawable.ic_launcher))
				.setContent(R.id.tab1));
		tabhost.addTab(tabhost
				.newTabSpec("calendar_tabhost two")
				.setIndicator(getResources().getString(id2),
						getResources().getDrawable(R.drawable.ic_launcher))
				.setContent(R.id.tab2));
		TabHostUtils.SetTabHost(this, tabhost);
		tabhost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {

			@Override
			public void onTabChanged(String arg0) {

				switch (tabhost.getCurrentTab()) {
				case 0:
					Constants.is_initiator = true;
					calendarFragment.getCalendarAdapter(new getAdapter() {

						@Override
						public void getAdapter(CalendarGridViewAdapter adapter) {
							adapter.notifyDataSetChanged();
						}
					});
					break;
				case 1:
					Constants.is_initiator = false;
					calendarFragment.getCalendarAdapter(new getAdapter() {

						@Override
						public void getAdapter(CalendarGridViewAdapter adapter) {
							adapter.notifyDataSetChanged();
						}
					});
					break;
				}
			}
		});

	}

	/**
	 * 要重写的第二处重写tabhost
	 * 
	 * @param id
	 * @param id2
	 * @param id3
	 */
	public void initTabHostTHREE(int id, int id2, int id3) {
		tabhost.setVisibility(View.GONE);
		tabhost2.setVisibility(View.VISIBLE);
		tabhost2.setup();
		tabhost2.addTab(tabhost2
				.newTabSpec("RigionPicture_tabhost one")
				.setIndicator(getResources().getString(id),
						getResources().getDrawable(R.drawable.ic_launcher))
				.setContent(R.id.tab1));
		tabhost2.addTab(tabhost2
				.newTabSpec("RigionPicture_tabhost two")
				.setIndicator(getResources().getString(id2),
						getResources().getDrawable(R.drawable.ic_launcher))
				.setContent(R.id.tab2));

		tabhost2.addTab(tabhost2
				.newTabSpec("RigionPicture_tabhost three")
				.setIndicator(getResources().getString(id3),
						getResources().getDrawable(R.drawable.ic_launcher))
				.setContent(R.id.tab3));
		tabhost2.addTab(tabhost2
				.newTabSpec("RigionPicture_tabhost four")
				.setIndicator(getResources().getString(R.string.Deaeline),
						getResources().getDrawable(R.drawable.ic_launcher))
				.setContent(R.id.tab4));
		TabHostUtils.SetTabHost(this, tabhost2);
		tabhost2.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
			@Override
			public void onTabChanged(String arg0) {
				switch (tabhost2.getCurrentTab()) {
				case 0:
					initListFragment(0);
					break;
				case 1:
					initListFragment(1);
					break;
				case 2:
					initListFragment(2);
					break;
				case 3:
					initListFragment(3);
					break;
				}
			}
		});
	}

	protected boolean ShowStartButton(int Y, int M, int D, int YY, int MM,
			int DD) {
		if (YY == Y && MM == M && DD == D) {
			return true;
		} else {
			return false;
		}
	}

	protected boolean ShowEndButton(int Y, int M, int D, int YY, int MM, int DD) {
		if (YY == Y && MM == M && DD == D) {
			return true;
		} else {
			return false;
		}
	}

	public String ShowActivity(int Y, int M, int D,
			List<Activity_Overview_Model> models) {
		for (int i = 0; i < models.size(); i++) {
			if (Y == BackYear(models.get(i).getStart_time())
					&& M == BackMonth(models.get(i).getStart_time())
					&& D == BackDay(models.get(i).getStart_time())) {
				return getResources().getString(R.string.l_xb40)
						+ panduan(Y, M, D, models)
						+ getResources().getString(R.string.l_xb41);
			}
		}
		return null;
	}

	/**
	 * 判断共有多少个活动
	 * 
	 * @param Y
	 * @param M
	 * @param D
	 * @param models
	 * @return
	 */
	private int panduan(int Y, int M, int D,
			List<Activity_Overview_Model> models) {
		int num = 0;
		Constants.temp_num = new ArrayList<Integer>();
		for (int i = 0; i < models.size(); i++) {
			if (Y == BackYear(models.get(i).getStart_time())
					&& M == BackMonth(models.get(i).getStart_time())
					&& D == BackDay(models.get(i).getStart_time())) {
				Constants.temp_num.add(i);
				++num;
			}
		}
		Constants.temp_map.put(Y + "-" + M + "-" + D, Constants.temp_num);
		// Constants.temp_list.add(Constants.temp_num);
		return num;
	}

	// 将时间中的年份提取出来并转换为int
	public static int BackYear(String time) {
		if (time != null) {
			return Integer.valueOf(time.substring(0, 4));
		} else {
			return 0;
		}

	}

	// 将时间中的月份提取出来并转换为int
	public static int BackMonth(String time) {
		if (time != null) {
			return Integer.valueOf(time.substring(5, 7));
		} else {
			return 0;
		}
	}

	// 将时间中的日提取出来并转换为int
	public static int BackDay(String time) {
		if (time != null) {
			return Integer.valueOf(time.substring(8, time.length()));
		} else {
			return 0;
		}
	}

	private void li_activity_show(final String start_ti, final String end_ti) {
		Utils.showPrgress(CalendarMyActivityActivity.this);
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("start", start_ti);
				map.put("end", end_ti);
				map.put("uid", uid);
				map.put("cid", "0");
				map.put("fid", Utils.getUid(CalendarMyActivityActivity.this));
				map.put("languageType",
						com.badibadi.mytools.Dialog
								.getSystemLanguageTypegrzx(CalendarMyActivityActivity.this));
				String t_content = Utils.sendRequest(map, Constants.BadiUrl
						+ "li_activity_show");
				if (t_content != null) {
					//    ("返回期间的活动是:" + t_content);
					results = Utils.checkResult_NNN(getApplicationContext(),
							t_content);
					if (results != null && !results.getRetmsg().equals("null")) {
						try {
							overview_Models_starttt = JSONUtils
									.getListByJsonString(results.getRetmsg(),
											Activity_Overview_Model.class);
							handler.sendEmptyMessage(3);
						} catch (JSONException e) {
							   
						}
					} else {
						handler.sendEmptyMessage(3);
					}
				} else {
					handler.sendEmptyMessage(3);
				}
			}
		});
	}

	/**
	 * 获取当前时间日期的Data
	 * 
	 * @param timetime
	 * @return
	 * @throws ParseException
	 */
	private Date Get___Data(String timetime) throws ParseException {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Date date;
		date = df.parse(timetime);
		return date;
	}

	/**
	 * 要在日历中加入数据在这里改
	 */
	private void initCalendarFragment() {
		try {
			li_activity_show(Utils.getFirstday_Month(
					Get___Data(Utils.GetSystemCurrentTime1(calendar)), 0),
					Utils.getLastday_Month(
							Get___Data(Utils.GetSystemCurrentTime1(calendar)),
							0));
		} catch (ParseException e) {
			   
		}
	}

	protected void initOnCalendarItemClistener(AdapterView<?> arg0, View view,
			int position, long arg3, CalendarGridViewAdapter calendaradapter) {

		//    
		Toast.makeText(CalendarMyActivityActivity.this,
				"" + calendaradapter.getYearMonthDay(position), 0).show();
		//    
		if (backdd(Constants.temp_map,
				calendaradapter.getYearMonthDay(position)).size() > 0) {
			Intent intent = new Intent(this, Data_Me_Activity.class);
			// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.putExtra("日期", calendaradapter.getYearMonthDay(position));
			intent.putExtra("uid", uid);
			intent.putExtra("fid", fid);
			startActivity(intent);
		} else {

		}
		// }

	}

	/**
	 * 匹配当前时间是否有活动
	 * 
	 * @param map匹配的map
	 * @param time传入需要匹配的时间
	 */
	public List<Integer> backdd(Map<String, Object> map, String time) {
		Set<Map.Entry<String, Object>> set = map.entrySet();
		// boolean jud = false;
		List<Integer> integers = new ArrayList<Integer>();
		for (Iterator<Map.Entry<String, Object>> it = set.iterator(); it
				.hasNext();) {
			Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it
					.next();
			//    (entry.getKey() + "--->" +
			// entry.getValue());
			if (Utils.getStringMillis(time) == Utils.getStringMillis(entry
					.getKey())) {
				// jud = true;
				integers = (List<Integer>) entry.getValue();
			}
		}
		Constants.temp_num = integers;
		return integers;
	}

	/**
	 * 根据num判断读取的是哪一个Fragment
	 * 
	 * @param num
	 *            0读取日历模式 1读取列表模式
	 */
	private void LoadFragment(int num) {
		if (num == 0) {
			models.clear();
			models_1.clear();
			initCalendarFragment();
		} else if (num == 1) {
			models.clear();
			models_1.clear();
			initListFragment(0);
		}
	}

	/**
	 * 列表的Fragment
	 */
	private void initListFragment(int t) {
		is_rili = false;
		FragmentTransaction transaction = manager.beginTransaction();
		fragment0 = ActivityMyActivityFragment0.getInstance();
		bun = new Bundle();
		bun.putString("uid", uid);
		bun.putString("fid", fid);
		bun.putInt("type", t);//这边传的一个key值过去
		fragment0.setArguments(bun);
		transaction.replace(R.id.calendar_layout, fragment0);
		transaction.commit();
	}

	/**
	 * 在这里是否要隐藏搜索关键字的和类别的
	 * 
	 * @param ll
	 * @param visible
	 *            0 Visible -1 gone 1 VISIBLE
	 */
	public void GoneOrVisibleSearchEdiTText(LinearLayout ll, int visible) {
		if (visible == 1) {
			ll.setVisibility(View.VISIBLE);
		} else if (visible == -1)
			ll.setVisibility(View.GONE);
		else if (visible == 0) {
			ll.setVisibility(View.INVISIBLE);
		}

	}

	private void init() {
		this.findViewById(R.id.calendar_index_btn).setOnClickListener(this);
		calendar_title = (TextView) findViewById(R.id.calendar_title);
		tabhost = (TabHost) findViewById(R.id.calendar_tabhost);
		tabhost2 = (TabHost) findViewById(R.id.RigionPicture_tabhost);

		bottom_btn1 = (RelativeLayout) findViewById(R.id.calender_bottom_btn1);
		bottom_btn2 = (RelativeLayout) findViewById(R.id.calender_bottom_btn2);
		bottom_btn1.setSelected(false);
		bottom_btn2.setSelected(true);
		models = new ArrayList<Activity_Overview_Model>();
		models_1 = new ArrayList<Activity_Overview_Model>();
		overview_Models_starttt = new ArrayList<Activity_Overview_Model>();
		calendar = Calendar.getInstance();
		this.findViewById(R.id.calendar_return_btn).setOnClickListener(this);
		initTabHostTWO(R.string.Sponsor, R.string.Partake);
		initTabHostTHREE(R.string.Newest, R.string.Hottest, R.string.Create);
		ChangeToThreeTab();

	}

	/**
	 * 底部日历模式的点击事件
	 * 
	 * @param view
	 */
	public void OnClick0(View view) {
		if (view.isSelected() != true) {
			view.setSelected(true);
			bottom_btn2.setSelected(false);
			LoadFragment(0);
			OnChageTabHost0();
		}
	}

	/**
	 * 底部列表的点击事件
	 * 
	 * @param view
	 */
	public void OnClick1(View view) {
		if (view.isSelected() != true) {
			view.setSelected(true);
			bottom_btn1.setSelected(false);
			LoadFragment(1);
			OnChageTabHost1();
		}
	}

	/**
	 * 必须重写
	 */
	public void OnChageTabHost0() {
		ChangeToTWOTab();
	}

	/**
	 * 必须重写
	 */
	public void OnChageTabHost1() {
		ChangeToThreeTab();
	}

	protected void ChangeToThreeTab() {

		tabhost.setVisibility(View.GONE);
		tabhost2.setVisibility(View.VISIBLE);
	}

	protected void ChangeToTWOTab() {

		// initTabHost(id,id2);
		tabhost2.setVisibility(View.GONE);
		tabhost.setVisibility(View.VISIBLE);

	}

	/**
	 * 隐藏掉所有的tabHost
	 */
	protected void GoneAllTabHost() {//Fragment
		tabhost2.setVisibility(View.GONE);
		tabhost.setVisibility(View.GONE);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.calendar_return_btn:
			// 必须重写，但是里面没有东西
			if (!is_rili) {
				fragment0.getSearchIsReturnUp(new getFragmentData() {
					@Override
					public void getIsReturnUp(boolean isReturn) {
						// 这里不用执行任何操作，在fragment中已经执行了
					}
				});
			} else {
				CalendarMyActivityActivity.this.finish();
			}
			break;
		case R.id.calendar_index_btn:
			Intent intent = new Intent(CalendarMyActivityActivity.this,
					IndexActivity.class);
			startActivity(intent);
			overridePendingTransition(R.anim.slide_left, R.anim.slide_right);

			break;
		default:
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		// 实现这个接口就能够使用返回上一级功能了
		case 4:
			if (!is_rili) {
				fragment0.getSearchIsReturnUp(new getFragmentData() {

					@Override
					public void getIsReturnUp(boolean isReturn) {
						// 这里不用执行任何操作，在fragment中已经执行了

					}
				});
			} else {
				CalendarMyActivityActivity.this.finish();
			}
			break;

		}
		return true;
	}
}
